package cn.jekun.shop.web.service;

import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.DateJsonValueProcessor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.Num;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.ErpDeliveryAddress;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.shop.common.service.ShopBaseService;
/**
 * 
 * @author twj
 *
 */
@Service(AddressService.BEAN_NAME)
public class AddressService extends ShopBaseService{
	public static final String BEAN_NAME = "cn.jekun.shop.web.service.AddressService";
	@Override
	public String getNamespace() {
		return "ERP_DELIVERY_ADDRESS";
	}
	/**
	 * 
	 * @param userId 用户代码
	 * @param provinceId 省份代码
	 * @param cityId 城市代码
	 * @param regionId 区域代码
	 * @param street 街道
	 * @param shipName 收货人姓名
	 * @param shipZip 邮编
	 * @param shipTel 电话号码
	 * @param mobile 手机号码
	 * @param def 默认 （0为非默认，1为默认）
	 * @param memo 备注
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	public JSONObject save(@RsUser.AnnoUserId String userId,@ErpDeliveryAddress.AnnoProvinceId String provinceId,@ErpDeliveryAddress.AnnoCityId String cityId,@ErpDeliveryAddress.AnnoRegionId String regionId,@ErpDeliveryAddress.AnnoStreet String street,@ErpDeliveryAddress.AnnoShipName String shipName,@ErpDeliveryAddress.AnnoShipZip String shipZip,@ErpDeliveryAddress.AnnoShipTel String shipTel,@ErpDeliveryAddress.AnnoShipMobile String mobile,@ErpDeliveryAddress.AnnoDef String def,@ErpDeliveryAddress.AnnoMemo String memo){
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		List resultList = new ArrayList();
		Map formMap = new HashMap();
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		if (StringUtils.isBlank(provinceId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"省份编码不能为空");
		}
		if (StringUtils.isBlank(cityId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"城市编码不能为空");
		}
		if (StringUtils.isBlank(regionId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"地区编码不能为空");
		}
		if (StringUtils.isBlank(street)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"街道地址不能为空");
		}
		if (StringUtils.isBlank(shipZip)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"邮编不能为空");
		}
		
		if (StringUtils.isBlank(shipName)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"收货人姓名不能为空");
		}
		
		if (StringUtils.isBlank(mobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"手机号不能为空");
		}
		if (StringUtils.isBlank(def)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"默认值字段不能为空");
		}
		if (StringUtils.isBlank(memo)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"备注不能为空");
		}
		Map totalMap = new HashMap();
		totalMap.put(ErpDeliveryAddress.COL_USER_ID, userId);
		totalMap.put(ErpDeliveryAddress.COL_AVAILABLE, "1");
		SqlUtis.prepareSql(totalMap, "", SqlUtis.getSQL(totalMap, "a."
				+ ErpDeliveryAddress.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ),
				SqlUtis.getSQLRequired(totalMap, "a."
						+ ErpDeliveryAddress.COL_AVAILABLE, Types.VARCHAR,SqlUtis.EQ));
		List list = this.list(totalMap);
		if(list.size()>=5){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"不能超过5条收货地址");
		}
		//如果添加地址为默认地址则需要更新该用户对应的其他所有地址设置为非默认
		if(def.equals("1")){
			Map tempAddressMap = new HashMap();
			tempAddressMap.put(ErpDeliveryAddress.COL_USER_ID, userId);
			SqlUtis.prepareSql(tempAddressMap, "", SqlUtis.getSQL(tempAddressMap, "a."
					+ ErpDeliveryAddress.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ));
			List<ErpDeliveryAddress> tempList = this.list(tempAddressMap);
			if(tempList!=null){
				ErpDeliveryAddress tempAddress = new ErpDeliveryAddress();
				tempAddress.setDef("0");
				tempAddressMap.put("erpDeliveryAddress", tempAddress);
				SqlUtis.prepareSql(tempAddressMap, "", SqlUtis.getSQL(tempAddressMap, "a."
						+ ErpDeliveryAddress.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ)
						);
				this.update(tempAddressMap);
			}
		}
		ErpDeliveryAddress address = new ErpDeliveryAddress();
		address.setAvailable("1");
		address.setUserId(userId);
		address.setProvinceId(provinceId);
		address.setCityId(cityId);
		address.setRegionId(regionId);
		address.setStreet(street);
		address.setShipName(shipName);
		address.setShipZip(shipZip);
		address.setShipTel(shipTel);
		address.setShipMobile(mobile);
		address.setDef(def);
		address.setMemo(memo);
		formMap.put("erpDeliveryAddress", address);
		String returnId = this.insert(formMap).toString();
		if(returnId==null){
			return executeRerutnFail(jsonObject);
		}else{
		return executeRerutn(jsonObject);
		}
	}
	/**
	 * 名为删除实则是update有效标志位为0
	 * @param addressId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	public JSONObject del(@ErpDeliveryAddress.AnnoAddressId String addressId){
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		List resultList = new ArrayList();
		Map formMap = new HashMap();
		if (StringUtils.isBlank(addressId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"地址编码不能为空");
		}
		formMap.put(ErpDeliveryAddress.COL_ADDRESS_ID, addressId);
		ErpDeliveryAddress address = new ErpDeliveryAddress();
		address.setAvailable("0");
		formMap.put("erpDeliveryAddress", address);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ ErpDeliveryAddress.COL_ADDRESS_ID, Types.VARCHAR,SqlUtis.EQ));
		int total = this.update(formMap);//返回update的条数
		if(total == 0){
			return executeRerutnFail(jsonObject);
		}else{
		return executeRerutn(jsonObject);
		}
	}
	/**
	 * 加载收货地址信息
	 * @param addressId 收货地址编码
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public JSONObject load(@ErpDeliveryAddress.AnnoAddressId String addressId){
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		List resultList = new ArrayList();
		Map formMap = new HashMap();
		if (StringUtils.isBlank(addressId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"地址编码不能为空");
		}
		formMap.put(ErpDeliveryAddress.COL_ADDRESS_ID, addressId);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ ErpDeliveryAddress.COL_ADDRESS_ID, Types.VARCHAR,SqlUtis.EQ));
		ErpDeliveryAddress address = this.one(formMap);
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONObject json =  JSONObject.fromObject(address, jsonConfig);
		jsonObject.put("address", json);
		return executeRerutn(jsonObject);
	}
	/**
	 * 查询收货地址
	 * @param pageSize 页大小
	 * @param currentPage 当前页
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public JSONObject query(@Num(length=10,message="每页条数格式不正确") String pageSize,@Num(length=10,message="页码格式不正确") String currentPage,@RsUser.AnnoUserId String userId){
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		List resultList = new ArrayList();
		Map formMap = new HashMap();
		if (StringUtils.isNotBlank(pageSize)) {
			page.setPageSize(Integer.parseInt(pageSize));
		}
		if (StringUtils.isNotBlank(currentPage)) {
			page.setPageNumber(Integer.parseInt(currentPage));
		}
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		
		
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd")); 
		formMap.put(ErpDeliveryAddress.COL_AVAILABLE, "1");//查有效标识位
		formMap.put(ErpDeliveryAddress.COL_USER_ID, userId);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ ErpDeliveryAddress.COL_AVAILABLE, Types.VARCHAR,SqlUtis.EQ),
				SqlUtis.getSQL(formMap, "a."
						+ ErpDeliveryAddress.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ));
		JSONArray jsonArray = JSONArray.fromObject(this.list(formMap, page), jsonConfig);
		jsonObject.put("addressList", jsonArray);
		jsonObject.put("totals", page.getTotalCount());
		return executeRerutn(jsonObject);
	}
	/**
	 * 名为修改实则update有效标识为0另外添加一条新的数据
	 * @param addressId 收货地址编码
	 * @param userId 用户代码
	 * @param provinceId 省份代码
	 * @param cityId 城市代码
	 * @param regionId 区域代码
	 * @param street 街道
	 * @param shipName 收货人姓名
	 * @param shipZip 邮编
	 * @param shipTel 电话号码
	 * @param mobile 手机号码
	 * @param def 默认 （0为非默认，1为默认）
	 * @param memo 备注
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	public JSONObject update(@ErpDeliveryAddress.AnnoAddressId String addressId,@ErpDeliveryAddress.AnnoUserId String userId,@ErpDeliveryAddress.AnnoProvinceId String provinceId,@ErpDeliveryAddress.AnnoCityId String cityId,@ErpDeliveryAddress.AnnoRegionId String regionId,@ErpDeliveryAddress.AnnoStreet String street,@ErpDeliveryAddress.AnnoShipName String shipName,@ErpDeliveryAddress.AnnoShipZip String shipZip,@ErpDeliveryAddress.AnnoShipTel String shipTel,@ErpDeliveryAddress.AnnoShipMobile String mobile,@ErpDeliveryAddress.AnnoDef String def,@ErpDeliveryAddress.AnnoMemo String memo){
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		List resultList = new ArrayList();
		Map formMap = new HashMap();
		if (StringUtils.isBlank(addressId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"地址编码不能为空");
		}
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		if (StringUtils.isBlank(provinceId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"省份编码不能为空");
		}
		if (StringUtils.isBlank(cityId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"城市编码不能为空");
		}
		if (StringUtils.isBlank(regionId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"地区编码不能为空");
		}
		if (StringUtils.isBlank(street)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"街道地址不能为空");
		}
		if (StringUtils.isBlank(shipZip)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"邮编不能为空");
		}
		
		if (StringUtils.isBlank(shipName)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"收货人姓名不能为空");
		}
		
		if (StringUtils.isBlank(shipTel)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"联系电话不能为空");
		}
		if (StringUtils.isBlank(def)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"默认值字段不能为空");
		}
		if (StringUtils.isBlank(memo)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"备注不能为空");
		}
		//1：先update记录
		formMap.put(ErpDeliveryAddress.COL_ADDRESS_ID, addressId);
		ErpDeliveryAddress address = new ErpDeliveryAddress();
		address.setAvailable("0");
		formMap.put("erpDeliveryAddress", address);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ ErpDeliveryAddress.COL_ADDRESS_ID, Types.VARCHAR,SqlUtis.EQ));
		int result = this.update(formMap);
		System.out.println(result);
		//2:再添加一条记录
		//如果编辑地址为默认地址则需要更新该用户对应的其他所有地址设置为非默认
		if(def.equals("1")){
			Map tempAddressMap = new HashMap();
			tempAddressMap.put(ErpDeliveryAddress.COL_USER_ID, userId);
			SqlUtis.prepareSql(tempAddressMap, "", SqlUtis.getSQL(tempAddressMap, "a."
					+ ErpDeliveryAddress.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ));
			List<ErpDeliveryAddress> tempList = this.list(tempAddressMap);
			if(tempList!=null){
				ErpDeliveryAddress tempAddress = new ErpDeliveryAddress();
				tempAddress.setDef("0");
				tempAddressMap.put("erpDeliveryAddress", tempAddress);
				SqlUtis.prepareSql(tempAddressMap, "", SqlUtis.getSQL(tempAddressMap, "a."
						+ ErpDeliveryAddress.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ)
						);
				this.update(tempAddressMap);
			}
		}
		ErpDeliveryAddress address1 = new ErpDeliveryAddress();
		address1.setAvailable("1");
		address1.setUserId(userId);
		address1.setProvinceId(provinceId);
		address1.setCityId(cityId);
		address1.setRegionId(regionId);
		address1.setStreet(street);
		address1.setShipName(shipName);
		address1.setShipZip(shipZip);
		address1.setShipTel(shipTel);
		address1.setDef(def);
		address1.setMemo(memo);
		address1.setShipMobile(mobile);
		formMap.put("erpDeliveryAddress", address1);
		String returnId = this.insert(formMap).toString();
		System.out.println(returnId);
		if(returnId==null){
			return executeRerutnFail(jsonObject);
		}else{
		return executeRerutn(jsonObject);
		}
	}
	

}
